<template>
  <div class="user-page">
    <!-- search组件 -->
    <div v-if="headShow">
      <header-search @reset="handlerReset" @search="handlerSearch">
        <template #search>
          <el-form-item label="用户名" size="small">
            <el-input
              v-model="queryData.username"
              clearable
              placeholder="请输入用户名"
            />
          </el-form-item>
          <el-form-item label="手机号" size="small">
            <el-input
              v-model="queryData.mobile"
              clearable
              placeholder="请输入手机号"
            />
          </el-form-item>
          <el-form-item label="性别" size="small">
            <el-select v-model="queryData.sex">
              <el-option label="男" :value="0" />
              <el-option label="女" :value="1" />
            </el-select>
          </el-form-item>
        </template>
      </header-search>
    </div>
    <!-- button组件 -->
    <header-button
      :head-show.sync="headShow"
      :check-data.sync="checkData"
      @open="visible = true"
      @loading="handlerLoading"
    />
    <!-- 表格 -->
    <el-table
      v-loading="loading"
      :data="tableData"
      border
      element-loading-text="拼命加载中"
      element-loading-spinner="el-icon-loading"
    >
      <el-table-column label="#" type="index" width="50px" />
      <el-table-column v-if="checkData[0].isckecked" prop="id" label="用户ID" />
      <el-table-column v-if="checkData[1].isckecked" prop="username" label="用户名" />
      <el-table-column v-if="checkData[2].isckecked" prop="mobile" label="手机号" />
      <el-table-column v-if="checkData[3].isckecked" prop="icon" label="用户头像">
        <template slot-scope="scope">
          <el-image
            v-if="scope.row.icon"
            style="width: 120px; height: 60px"
            :src="$ImgUrl + scope.row.icon"
            fit="fill"
          />
        </template>
      </el-table-column>
      <el-table-column v-if="checkData[4].isckecked" prop="sex" label="性别">
        <template slot-scope="scope">
          <el-tag v-if="+scope.row.sex === 0">男</el-tag>
          <el-tag v-else type="success">女</el-tag>
        </template>
      </el-table-column>
      <el-table-column v-if="checkData[5].isckecked" prop="birthday" label="出生年月" />
      <el-table-column label="操作" align="center">
        <template #default="{ row }">
          <el-button
            type="primary"
            icon="el-icon-edit"
            circle
            @click="handlerEdit(row.id)"
          />
          <el-button
            type="danger"
            icon="el-icon-delete"
            circle
            @click="handlerDel(row.id)"
          />
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页组件 -->
    <lay-page
      :limit.sync="queryData.limit"
      :page.sync="queryData.page"
      :count="count"
    />
    <!-- 对话================================ -->
    <el-dialog :visible.sync="visible" width="45%" :before-close="handleClose">
      <!-- 表单 -->
      <div slot="title" class="header-title">
        <!-- <div>添加分类</div> -->
        <div>{{ formData.id ? "修改用户" : "添加用户" }}</div>
      </div>
      <el-form ref="formRef" size="medium" :model="formData" :rules="rules">
        <el-row>
          <el-col :span="12">
            <el-form-item label="用户名" label-width="80px" prop="username">
              <el-input
                v-model.trim="formData.username"
                placeholder="请输入用户名称"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="手机号" label-width="80px" prop="mobile">
              <el-input
                v-model.trim="formData.mobile"
                placeholder="请输入手机号"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item v-if="formData.id" label="密码" label-width="80px">
              <el-input
                v-model="formData.password"
                placeholder="密码留空表示不修改"
              />
            </el-form-item>
            <el-form-item
              v-else
              label="密码"
              label-width="80px"
              prop="password"
            >
              <el-input
                v-model="formData.password"
                placeholder="请输入密码"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="性别" label-width="80px" prop="sex">
              <el-switch
                v-model="formData.sex"
                inactive-value="1"
                active-value="0"
                inactive-text="女"
                active-text="男"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="用户头像" prop="icon" label-width="80px">
              <el-upload
                ref="upload"
                class="upload-demo"
                action="http://124.223.14.236:8060/admin/common/upload?type=images"
                :limit="1"
                :file-list="fileList"
                list-type="picture"
                auto-upload
                :headers="headerObj"
                :on-remove="fileRemove"
                :on-success="fileSuccess"
              >
                <el-button
                  v-if="btnisShow"
                  size="small"
                  type="primary"
                >点击上传</el-button>
              </el-upload>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <span slot="footer">
        <el-button @click="handleClose">取 消</el-button>
        <el-button type="primary" autofocus @click="submit">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  getUserListApi,
  addUserApi,
  editUserApi,
  getUserInfoApi,
  delUserApi
} from '@/api/member'
import { getToken } from '@/utils/storage'
export default {
  name: 'UserPage',
  data() {
    return {
      loading: false,
      btnisShow: true,
      visible: false,
      headShow: true,
      queryData: {
        sex: '',
        username: '',
        mobile: '',
        page: 1,
        limit: 10
      },
      count: 0,
      tableData: [],
      formData: {
        icon: '',
        mobile: '',
        password: '',
        sex: '0',
        username: ''
      },
      rules: {
        username: [
          { required: true, message: '用户名类型必须！', trigger: ['blur'] }
        ],
        mobile: [
          { required: true, message: '手机号类型必须！', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '密码类型必须！', trigger: 'blur' }
        ],
        sex: [{ required: true, message: '标题类型必须！', trigger: 'blur' }],
        icon: [
          {
            required: true,
            message: '链接图片类型必须！',
            trigger: ['blur', 'change']
          }
        ]
      },
      fileList: [],
      headerObj: {
        'X-Token': getToken()
      },
      checkData: [
        { id: 1, name: '用户ID', isckecked: true },
        { id: 2, name: '用户名', isckecked: true },
        { id: 3, name: '手机号', isckecked: true },
        { id: 4, name: '用户头像', isckecked: true },
        { id: 5, name: '性别', isckecked: true },
        { id: 6, name: '出身年月', isckecked: true }
      ]
    }
  },
  watch: {
    'queryData.limit'(val) {
      this.initData()
    },
    'queryData.page'(val) {
      this.initData()
    }
  },
  created() {
    this.initData()
  },
  methods: {
    // 获取会员列表
    async initData() {
      const res = await getUserListApi(this.queryData)
      console.log(res)
      this.tableData = res.data
      this.count = res.count
    },
    // 刷选
    handlerSearch() {
      this.initData()
    },
    // 筛选重置
    handlerReset() {
      this.queryData = {
        sex: '',
        username: '',
        mobile: '',
        page: 1,
        limit: 10
      }
      this.initData()
    },
    // 删除
    handlerDel(id) {
      this.$confirm('确认删除？')
        .then(async(_) => {
          await delUserApi(id)
          this.$message.success('删除成功！')
          if (this.queryData.page > 1 && this.tableData.length === 1) {
            this.queryData.page--
          }
          this.initData()
        })
        .catch((_) => {})
    },
    // 编辑回显
    async handlerEdit(id) {
      this.fileList = []
      this.visible = true
      const res = await getUserInfoApi(id)
      // 回显的数组
      this.fileList.push({ url: this.$ImgUrl + res.icon })
      this.formData = {
        ...res
      }
      this.formData.sex = this.formData.sex.toString()
      if (this.fileList.length > 0) this.btnisShow = false
    },
    // 关闭对话框
    handleClose(done) {
      console.log(111)
      this.$confirm('确认关闭？')
        .then((_) => {
          this.dialogClose()
        })
        .catch((_) => {})
    },
    // 关闭对话框 清空表单
    dialogClose() {
      this.visible = false
      this.formData = {
        icon: '',
        mobile: '',
        password: '',
        sex: '0',
        username: ''
      }
      // 清空文件列表
      this.$refs.upload.clearFiles()
      // 清空表单校验
      this.$refs.formRef.clearValidate()
    },
    // 表单提交
    async submit() {
      try {
        await this.$refs.formRef.validate()
        this.formData.id
          ? await editUserApi(this.formData)
          : await addUserApi(this.formData)
        this.$message.success(this.formData.id ? '修改成功！' : '添加成功！')
        this.dialogClose()
        this.initData()
      } catch (err) {
        console.log(err)
      }
    },
    // 文件删除触发
    fileRemove(uploadFile, fileList) {
      this.btnisShow = true
      this.formData.icon = ''
      this.$refs.formRef.validateField('img')
    },
    // 文件上传成功触发
    fileSuccess(response, file, fileList) {
      this.btnisShow = false
      this.formData.icon = response.data.savePath
    },
    // 设置刷新loading
    async handlerLoading() {
      this.tableData = []
      this.loading = true
      await this.initData()
      this.loading = false
    }
  }
}
</script>

<style lang="less" scoped>
.user-page {
  padding: 20px;
  background-color: #fff;
}
/deep/ .el-dialog__header {
  background: #fafafa;
  font-size: 18px;
  font-weight: 600;
}
/deep/ .el-form-item__label {
  font-size: 14px;
  color: #606266;
  font-weight: 700;
}

.el-table {
  margin-top: 10px;
}
</style>
